package http;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.Toast;


import bean.BaseResponse;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 抽象类实现Observer（如果使用的是gson解析，就需要用到这个）
 *
 * @param <T>
 */
public abstract class BaseObserver<T> implements Observer<BaseResponse<T>> {
    private static final String TAG = "wh";
    private Context mContext;

    public BaseObserver(Context mContext) {
        this.mContext = mContext;
    }


    @Override
    public void onSubscribe(Disposable d) {
        if (!isConnected(mContext)) {
            Toast.makeText(mContext, "未连接网络", Toast.LENGTH_SHORT).show();
            if (d.isDisposed()) {
                d.dispose();
            }
        }
    }

    @Override
    public void onNext(BaseResponse<T> response) {
        //在这边对 基础数据 进行统一处理  举个例子：
        if (response.getrCode().equals("0")) {
            onSuccess(response.getrData());
        } else {
            onFailure(null, response.getMessage() + "==" + response.getrCode());
        }
    }

    @Override
    public void onError(Throwable e) {
        onFailure(e, RxExceptionUtil.exceptionHandler(e));
    }

    @Override
    public void onComplete() {

    }

    public abstract void onSuccess(T mode);

    public abstract void onFailure(Throwable e, String errorMsg);


    /**
     * 是否有网络连接，不管是wifi还是数据流量
     *
     * @param context
     * @return
     */
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info == null) {
            return false;
        }
        boolean available = info.isAvailable();
        return available;
    }
}
